package com.longlonggo.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5工具类
 * @author me@longlonggo.com
 * @version 100-000-000<br/>
 * 创建日期：2018年7月8日 <br/>
 * 历史修订：<br/>
 */
public class Md5Util {

    public static void main(String[] args) throws Exception{
        String passwd = "123456";

        String shaPsd = SHADes(passwd);
        System.out.println("----shaPsd: " + shaPsd);
//        String shaPsd2 = getSHA256Str(passwd);
//        System.out.println("----shaPsd2: " + shaPsd2);
//
//        System.out.println(shaPsd.equals(shaPsd2));

    }

    public static String SHADes(String sPassWord) throws Exception{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(sPassWord.getBytes("GBK"));
        return bytes2Hex(digest.digest());
    }

    /**
     * 将byte转为16进制
     * @param bts
     * @return
     */
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    /**
     　　* 将byte转为16进制
     　　* @param bytes
     　　* @return
     　　*/
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }


    /**
     　　* 利用java原生的摘要实现SHA256加密
     　　* @param str 加密后的报文
     　　* @return
     　　*/
    public static String getSHA256Str(String str){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("GBK"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

}
